package friendService

import (
	"chart.zozoo.net/app/models"
	"chart.zozoo.net/core/myRedis"
	"chart.zozoo.net/core/mysql"
	"encoding/json"
	"errors"
	"gorm.io/gorm"
	"strconv"
)

// Info 获取好友信息
func Info(uid, fid int, params ...string) (uf *models.UserFriends, err error) {
	uf = new(models.UserFriends)
	redisKey := "userFriends:uid:" + strconv.Itoa(uid) + ":fid:" + strconv.Itoa(fid) + ":json"

	if len(params) > 0 {
		switch params[0] {
		case "update":
			break
		case "delete":
			//删除好友，需要互相删除
			myRedis.RedisClient.Del(redisKey)
			redisKey = "userFriends:uid:" + strconv.Itoa(fid) + ":fid:" + strconv.Itoa(uid) + ":json"
			myRedis.RedisClient.Del(redisKey)
			return nil, nil
		default:
			res := myRedis.RedisClient.Get(redisKey)
			val := res.Val()
			if val != "" {
				err = json.Unmarshal([]byte(val), uf)
				if err != nil {
					return nil, err
				}

				return uf, nil
			}

		}
	}

	//查询数据库
	row := mysql.MysqlClient.Select("uid", "fid", "notes", "permission", "referer").
		Where("uid=? and fid=?", uid, fid).First(uf)
	if row.Error != nil && !errors.Is(row.Error, gorm.ErrRecordNotFound) {
		return nil, row.Error
	}

	if uf.Id == 0 {
		return nil, nil
	}

	return uf, nil
}
